package com.gzsxy.esjy.response.impl;


import com.gzsxy.esjy.common.Assert;
import com.gzsxy.esjy.response.HttpServletResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

/**
 * 默认业务响应
 * @author hezhiyuan
 *
 */
public class DefaultHttpServletResponse implements HttpServletResponse {

	
	private HttpHeaders headers ;
	
	private int status ;
	
	private Object response ;
	
	private OutputStream out  ;
	
	private ChannelHandlerContext context ;
	
	
	
	public DefaultHttpServletResponse(HttpHeaders headers, ChannelHandlerContext context) {
		super();
		this.headers = headers;
		this.context = context;
	}

	@Override
	public void setStatus(int status) {
		this.status = status ;
	}

	@Override
	public void setResponse(Object body) {
		this.response = body ;
	}

	@Override
	public void addHeader(String name, String value) {
		headers.add(name,value) ;
	}

	@Override
	public int getStatus() {
		return this.status;
	}

	@Override
	public Object getResponse() {
		return this.response;
	}

	@Override
	public OutputStream getOutPutStream() {
		Assert.notTrue(out == null, "NettyOutputStream is not to init times > 1 ");
		out = new OutputStream(context);
		HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.headers().add(headers) ;
		out.write(response);
		return out;
	}
	
	public boolean iswrited() {
		return out != null ;
	}

}
